package springapp.service;

import java.util.List;
import java.util.Set;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import springapp.dao.DesignationDao;
import springapp.entity.DesignationEntity;

@Service
public class DesignationService implements IServiceConstants,IDesignationService {

	@Autowired(required = true)
	private CacheService cacheService;

	@Autowired(required = true)
	private DesignationDao designationDao;

	private ICache<Integer, String> designationCache;

	@SuppressWarnings("unchecked")
	@PostConstruct
	public void initialise() {
		this.designationDao.setInitialized();
		List<DesignationEntity> entities = getAllEntities();
		this.cacheService.addToCache(entities, DESIGNATION);
		this.designationCache = (ICache<Integer, String>) this.cacheService
				.getCache(DESIGNATION);
		this.designationDao.unset();
	}
	
	@Transactional
	public List<DesignationEntity> getAllEntities(){
		List<DesignationEntity> allEntities = designationDao.getAllEntities();
		return allEntities;
	}

	public Integer getDesignationId(String designation) {
		Integer designationId = designationCache.getKeyForValue(designation);

		if (designationId == null) {
			DesignationEntity designationEntity = saveDesignation(designation);
			designationId = designationEntity.getId();
			designationCache.put(designationId, designation);
		}

		return designationId;
	}

	public String getDesignationName(Integer designationId) {
		return this.designationCache.getValueForKey(designationId);
	}

	public DesignationEntity getDesignationEntity(String designation) {
		Integer designationId = designationCache.getKeyForValue(designation);
		DesignationEntity entity = null;

		if (designationId == null) {
			entity = saveDesignation(designation);
			designationId = entity.getId();
			designationCache.put(designationId, designation);
		} else {
			entity = designationDao.getEntity(designationId);
		}

		return entity;

	}

	private DesignationEntity saveDesignation(String designation) {
		DesignationEntity designationEntity = new DesignationEntity();
		designationEntity.setDesignationName(designation);
		designationDao.saveEntity(designationEntity);
		return designationEntity;
	}

	public Set<String> getAllDesignations() {
		return this.designationCache.getValues();
	}

}
